<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var mctFromLeafValues = function (arr) {
      const n = arr.length;
      const stack = [];
      let res = 0;

      for (let i = 0; i < n; i++) {
        while (stack.length && (stack[stack.length - 1] <= arr[i] || i === n - 1)) {
          const bottom = stack.pop();
          if (stack.length) {
            res += Math.min(stack[stack.length - 1], arr[i]) * bottom;
          } else {
            res += bottom * arr[i];
          }
          arr[i] = Math.max(bottom, arr[i]);
        }
        stack.push(arr[i]);
      }

      return res;
    };
    console.log(mctFromLeafValues(arr = [6, 2, 4]))
  </script>
</body>

</html>